import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { getServerAuthSession } from "@/auth";
import Link from "next/link";
import { ArrowLeft, Heart, Bookmark, Share, MessageCircle } from "lucide-react";

interface PostDetailProps {
  params: Promise<{ id: string }>;
}

export default async function PostDetail({ params }: PostDetailProps) {
  const { id } = await params;
  
  const session = await getServerAuthSession();
  const userId = (session as any)?.user?.id;

  const post = await prisma.post.findUnique({
    where: { id },
    include: {
      author: {
        select: { name: true, image: true }
      },
      likes: userId ? { where: { userId } } : false,
      bookmarks: userId ? { where: { userId } } : false,
      _count: {
        select: {
          likes: true,
          bookmarks: true,
          views: true
        }
      }
    }
  });

  if (!post) {
    notFound();
  }

  const liked = Array.isArray(post.likes) ? post.likes.length > 0 : false;
  const bookmarked = Array.isArray(post.bookmarks) ? post.bookmarks.length > 0 : false;
  const tags: string[] = Array.isArray(post.tags) ? post.tags : [];
  const topics: string[] = Array.isArray(post.topics) ? post.topics : [];

  return (
    <div className="min-h-dvh bg-white">
      {/* 顶部导航 */}
      <header className="sticky top-0 z-10 bg-white/95 backdrop-blur-md border-b border-gray-100">
        <div className="max-w-screen-md mx-auto px-4 h-14 flex items-center gap-4">
          <Link
            href="/"
            className="p-2 -ml-2 rounded-full hover:bg-gray-100 transition-colors"
          >
            <ArrowLeft size={20} />
          </Link>
          <div className="flex-1">
            <h1 className="font-medium text-gray-900 truncate">详情</h1>
          </div>
          <button className="p-2 rounded-full hover:bg-gray-100 transition-colors">
            <Share size={20} className="text-gray-600" />
          </button>
        </div>
      </header>

      <div className="max-w-screen-md mx-auto">
        {/* 主图片 */}
        <div className="relative aspect-[4/5] bg-gray-100">
          {post.coverUrl && (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={post.coverUrl}
              alt={post.title}
              className="w-full h-full object-cover"
            />
          )}
        </div>

        {/* 内容区域 */}
        <div className="p-4 space-y-4">
          {/* 标题和标签 */}
          <div className="space-y-3">
            <h1 className="text-lg font-semibold text-gray-900 leading-tight">
              {post.title}
            </h1>
            
            {/* 标签 */}
            {(tags.length > 0 || topics.length > 0) && (
              <div className="flex flex-wrap gap-2">
                {[...tags, ...topics].map((tag, index) => (
                  <span
                    key={`${tag}-${index}`}
                    className="inline-block px-3 py-1 text-sm text-blue-600 bg-blue-50 rounded-full"
                  >
                    #{tag}
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* 内容 */}
          {post.content && (
            <div className="prose prose-sm max-w-none">
              <p className="text-gray-700 leading-relaxed whitespace-pre-line">
                {post.content}
              </p>
            </div>
          )}

          {/* 作者信息 */}
          <div className="flex items-center gap-3 py-4 border-t border-gray-100">
            <div className="w-10 h-10 rounded-full bg-gray-200 overflow-hidden">
              {post.author?.image ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={post.author.image}
                  alt={post.author.name || "用户头像"}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full bg-gradient-to-br from-purple-400 to-pink-400 flex items-center justify-center text-white font-semibold">
                  {(post.author?.name || "用户")[0]?.toUpperCase()}
                </div>
              )}
            </div>
            <div className="flex-1">
              <div className="font-medium text-gray-900">
                {post.author?.name || "匿名用户"}
              </div>
              <div className="text-sm text-gray-500">
                {new Date(post.createdAt).toLocaleDateString("zh-CN", {
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                })}
              </div>
            </div>
            <button className="px-4 py-2 text-sm font-medium xiaohongshu-gradient text-white rounded-full hover:opacity-90 transition-opacity">
              关注
            </button>
          </div>

          {/* 互动统计 */}
          <div className="flex items-center gap-6 py-2 text-sm text-gray-500">
            <span>{post._count.views} 浏览</span>
            <span>{post._count.likes} 点赞</span>
            <span>{post._count.bookmarks} 收藏</span>
          </div>
        </div>
      </div>

      {/* 底部操作栏 */}
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-100 safe-area-pb">
        <div className="max-w-screen-md mx-auto px-4 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-1">
              <button className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:bg-gray-50 rounded-full transition-colors">
                <MessageCircle size={20} />
                <span className="text-sm">评论</span>
              </button>
            </div>
            
            <div className="flex items-center gap-2">
              <button
                className={`flex items-center gap-2 px-4 py-2 rounded-full transition-all duration-200 ${
                  liked
                    ? "text-red-500 bg-red-50"
                    : "text-gray-600 hover:bg-gray-50"
                }`}
              >
                <Heart size={20} fill={liked ? "currentColor" : "none"} />
                <span className="text-sm font-medium">
                  {liked ? "已赞" : "点赞"}
                </span>
              </button>
              
              <button
                className={`flex items-center gap-2 px-4 py-2 rounded-full transition-all duration-200 ${
                  bookmarked
                    ? "text-amber-600 bg-amber-50"
                    : "text-gray-600 hover:bg-gray-50"
                }`}
              >
                <Bookmark size={20} fill={bookmarked ? "currentColor" : "none"} />
                <span className="text-sm font-medium">
                  {bookmarked ? "已收藏" : "收藏"}
                </span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 底部安全区域 */}
      <div className="h-20" />
    </div>
  );
}